package com.bst.etl.batch.reader;

import com.alibaba.druid.pool.DruidDataSource;
import com.bst.etl.utils.EtlUtil;
import com.bst.system.framework.datasource.DynamicDataSource;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.item.database.JdbcCursorItemReader;
import org.springframework.batch.item.database.builder.JdbcCursorItemReaderBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.ColumnMapRowMapper;

import java.util.Date;
import java.util.Map;

@Configuration
public class CursorReader {


    @Bean(name = "selfJdbcCursorItemReader",destroyMethod = "")
    @StepScope
    public JdbcCursorItemReader<Map<String,Object>> commonCursorReader(@Value("#{jobParameters[querySql]}") String querySql
            , @Value("#{jobParameters[idDbSou]}") String idDbSou
            , @Value("#{jobParameters[DT_DAY_BEGIN]}") Date startDate
            , @Value("#{jobParameters[DT_DAY_END]}") Date endDate) {
        DruidDataSource souDataSource = DynamicDataSource.getDataSourceById(idDbSou);
        String qSQL = EtlUtil.buildSql(querySql, startDate, endDate, souDataSource.getDbType());
        return new JdbcCursorItemReaderBuilder<Map<String,Object>>()
                .dataSource(souDataSource)
                .name("jdbcCursorItemReader")
                .sql(qSQL)
                .rowMapper(new ColumnMapRowMapper())
                .build();
    }
}
